package com.example.safeassistan.home.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.activity.HiddenDangerAdd;
import com.example.safeassistan.home.activity.HiddenDangerinvestigation;
import com.example.safeassistan.home.adapter.HiddenDangerInvestigationParentAdapter;
import com.example.safeassistan.home.listener.OnGroupExpandedListener;
import com.example.safeassistan.home.model.InvestigationModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.EventBusBean;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.ToastUtil;
import com.example.safeassistan.widget.CustomExpandableListView;
import com.example.safeassistan.widget.HiddendangerInvestigationDialog;
import com.example.safeassistan.widget.WarningDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

public class InvestagionFragment extends BaseVPFragment implements View.OnClickListener {
    private static final int REQUEST_CODE = 101;
    private Context context;
    private static final int REQUESTCODE=1111;
    private View view;
    private CustomExpandableListView rcView;
    private HiddenDangerInvestigationParentAdapter adapter;
    private List<InvestigationModel.ResultDTO> data;
    private LinearLayout llAllPass;


    private List<Map> itemIdList;
    private String checkTableId="";//检查表id
    private String dangerRiskPointId="";//危险源id
    private String riskPointId="";//风险点id
    private String defId="";//任务id
    private int parentPosi=0,childPosi=0;
    private String address="";


    public static InvestagionFragment newInstance(String  type,String riskPointId,String defId,String checkTableId) {
        Bundle arguments = new Bundle();
        arguments.putString("type",type);
        arguments.putString("riskPointId",riskPointId);
        arguments.putString("defId",defId);
        arguments.putString("checkTableId",checkTableId);
        InvestagionFragment fl = new InvestagionFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.investigation_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        Bundle bundle = getArguments();
        dangerRiskPointId=bundle.getString("type");
        riskPointId=bundle.getString("riskPointId");
        defId=bundle.getString("defId");
        checkTableId=bundle.getString("checkTableId");
        llAllPass=view.findViewById(R.id.llAllPass);
        rcView=view.findViewById(R.id.rcView);
        rcView.setGroupIndicator(null);

        itemIdList=new ArrayList<>();
        llAllPass.setOnClickListener(this);
        checkPermission();
    }


    public void getData(){
        JSONObject map=new JSONObject();
        try {
            map.put("defId",defId);
            map.put("checkTableId",checkTableId);
            if (!dangerRiskPointId.equals("")){
                map.put("dangerRiskPointId",dangerRiskPointId);
            }
            map.put("riskPointId",riskPointId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.queryAgendaTaskDetails, "", map,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean  success = jsonObject.getBoolean("success");
                    if (success) {
                        llAllPass.setVisibility(View.VISIBLE);
                        Object obj = JsonUtils.fromJson(result.toString(), InvestigationModel.class);
                        if (obj instanceof InvestigationModel) {
                            InvestigationModel  backLogListModel=(InvestigationModel) obj;
                            if(backLogListModel.getResult().size()>0){
                                //提交数据的列表长度固定
                                itemIdList=new ArrayList<>(backLogListModel.getResult().size());
                                for (int i=0;i<backLogListModel.getResult().size();i++){
                                    for (int j=0;j<backLogListModel.getResult().get(i).getChildren().size();j++){
                                        Map p=new HashMap();
                                        p.put("defRecordId",defId==null?"":defId);
                                        p.put("itemId",backLogListModel.getResult().get(i).getChildren().get(j).getId());
                                        p.put("status",backLogListModel.getResult().get(i).getChildren().get(j).getStatus()+"");
                                        itemIdList.add(p);
                                    }
                                }


                                for (int m=0;m<backLogListModel.getResult().size();m++){
                                    for (int n=0;n<backLogListModel.getResult().get(m).getChildren().size();n++){
                                        if (backLogListModel.getResult().get(m).getChildren().get(n).getStatus()!=0){
                                            llAllPass.setVisibility(View.VISIBLE);
                                            break;
                                        }else {
                                            llAllPass.setVisibility(View.GONE);
                                        }
                                    }
                                }

                                data=backLogListModel.getResult();
                                adapter=new HiddenDangerInvestigationParentAdapter(getContext(),data);
                                rcView.setAdapter(adapter);
                                rcView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                                    @Override
                                    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                                        return false;
                                    }
                                });
                                rcView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                                    @Override
                                    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                                        parentPosi=groupPosition;
                                        childPosi=childPosition;
                                        Intent intent=new Intent(context, HiddenDangerAdd.class);
                                        intent.putExtra("flag", REQUESTCODE);
                                        intent.putExtra("name",data.get(parentPosi).getChildren().get(childPosi).getItemDesc());
                                        intent.putExtra("itemId",data.get(parentPosi).getChildren().get(childPosi).getId());
                                        intent.putExtra("checkTableId",checkTableId);
                                        intent.putExtra("riskPointId",riskPointId);
                                        intent.putExtra("defRecordId",defId);
                                        intent.putExtra("checkAddress",address);
                                        startActivityForResult(intent, REQUESTCODE);
                                        return true;
                                    }
                                });
                                int groupCount = rcView.getCount();
                                for (int i=0; i<groupCount; i++) {
                                    rcView.expandGroup(i);
                                }
                                adapter.setOnGroupExpandedListener(new OnGroupExpandedListener() {
                                    @Override
                                    public void onGroupExpanded(int groupPosition) {
                                        HiddendangerInvestigationDialog dialog=new HiddendangerInvestigationDialog(getContext());
                                        dialog.setClicklistener(new HiddendangerInvestigationDialog.ClickListenerInterface() {
                                            @Override
                                            public void doActivity() {
                                                dialog.dismiss();
                                                data.get(groupPosition).setIsselect("true");
                                                rcView.expandGroup(groupPosition);
                                                adapter.notifyDataSetChanged();
                                            }

                                            @Override
                                            public void doNorelative() {
                                                dialog.dismiss();
                                                data.get(groupPosition).setIsselect("");
                                                rcView.collapseGroup(groupPosition);
                                                adapter.notifyDataSetChanged();
                                            }
                                        });
                                        dialog.show();
                                    }
                                });
                            }
                        }
                    }else {
                        llAllPass.setVisibility(View.GONE);
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upLoadSuccess(EventBusBean eventBus){
        if (eventBus.getCode()==100){
           // checkedTime=eventBus.getMsg();
            getData();
        }
}


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent p) {
        super.onActivityResult(requestCode, resultCode, p);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUESTCODE:
                    data.get(parentPosi).getChildren().get(childPosi).
                            setStatus(p.getIntExtra("type",0));
                    adapter.notifyDataSetChanged();
                    for (int m=0;m<data.size();m++){
                        for (int n=0;n<data.get(m).getChildren().size();n++){
                            if (data.get(m).getChildren().get(n).getStatus()!=0){
                                llAllPass.setVisibility(View.VISIBLE);
                                return;
                            }else {
                                llAllPass.setVisibility(View.GONE);
                            }
                        }
                    }
            }
        }
    }


    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            if (!EventBus.getDefault().isRegistered(this)){
                EventBus.getDefault().register(this);
            }

        }else {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        getData();
    }


    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llAllPass:
                //全部通过
                WarningDialog dialog1=new WarningDialog(getContext(),
                        "是否确定全部通过检查？","取消","确定","");
                dialog1.setClicklistener(new WarningDialog.ClickListenerInterface() {
                    @Override
                    public void doCancel() {
                        dialog1.dismiss();
                    }

                    @Override
                    public void doConfirm() {


                        for (int p=0;p<itemIdList.size();p++){
                            itemIdList.get(p).put("status",0);
                        }
                        submitData();
                    }
                });
                dialog1.show();
                break;
        }
    }

        public void submitData(){
        JSONObject map=new JSONObject();
        try {
            map.put("checkTableId",checkTableId);//检查表id
            map.put("riskPointId",riskPointId);//风险点id
            JSONArray g = new JSONArray(itemIdList);
            map.put("itemIdList",g);
            map.put("checkAddress",address);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.checkallSuccess, "", map, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {

                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean  success = jsonObject.getBoolean("success");
                    if (success) {
                        ToastUtil toastUtil=new ToastUtil(context,R.layout.popu_success,"已全部通过！！",1);
                        toastUtil.show();
                        for (int i=0;i<data.size();i++){
                            for (int j=0;j<data.get(i).getChildren().size();j++){
                                data.get(i).getChildren().get(j).
                                        setStatus(0);
                            }
                        }
                        adapter.notifyDataSetChanged();
                        llAllPass.setVisibility(View.GONE);
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int status, String msg) { }
        });
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    address=amapLocation.getAddress();
                    Log.e("address",address);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    public void initLocation(){

//初始化定位
        mLocationClient = new AMapLocationClient(context);
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }


    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("aaa", "onRequestPermissionsResult: " +
                            "权限申请成功");
                    for (int i : grantResults) {
                        Log.d("aaa", "onRequestPermissionsResult: " + i);
                    }
                    initLocation();
                } else {
                    Toast.makeText(context, "您已拒绝申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /****权限**/
    private void checkPermission(){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)!= PermissionChecker.PERMISSION_GRANTED||
                        PermissionChecker.checkSelfPermission(context,Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PermissionChecker.PERMISSION_GRANTED) {
                    // 不相等 请求授权
                    ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    },REQUEST_CODE);
                }else {
                    initLocation();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}